package com.tender.converter;

import com.tender.constants.Constants;
import com.tender.dto.HostInfoDTO;
import com.tender.utils.DataUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class RouterDiscoveryConverter {

    public static HostInfoDTO converter2HostInfoDTO(String applicationName, ServiceInstance serviceInstance) {
        if (StringUtils.isBlank(applicationName) || null == serviceInstance) {
            return null;
        }
        HostInfoDTO hostInfoDTO = new HostInfoDTO();
        hostInfoDTO.setHostInfo(serviceInstance.getHost() + ":" + serviceInstance.getPort());
        hostInfoDTO.setApplicationName(applicationName);
        hostInfoDTO.setHostId(StringUtils.substringAfter(applicationName, Constants.APPLICATION_NAME_PREFIX));

        return hostInfoDTO;
    }

    public static List<HostInfoDTO> converter2HostInfoDTOList(String applicationName, List<ServiceInstance> serviceInstanceList) {
        if (StringUtils.isBlank(applicationName) || CollectionUtils.isEmpty(serviceInstanceList)) {
            return new ArrayList<>();
        }

        return DataUtils.transform(serviceInstanceList, serviceInstance -> converter2HostInfoDTO(applicationName, serviceInstance));
    }

}
